package com.powernode.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import com.powernode.config.AliyunOSSConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;

/**
 * 文件上传接口控制层
 */
@Api(tags = "文件上传接口管理")
@RequestMapping("admin/file")
@RestController
public class FileController {
    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    /**
     * 上传文件到阿里云OSS存储
     * 1.接口要求请求方式必须是post请求
     * 2.接受文件的对象类型是MultipartFile该对象是SpringMVC提供的
     *
     * @return 文件上传后的URL地址
     */
    @ApiOperation("上传单个文件")
    @PostMapping("upload/element")
    public String uploadFile(MultipartFile file) throws ClientException {
        // 获取阿里云OSS服务的终点地址
        String endpoint = aliyunOSSConfig.getEndpoint();
        // 获取阿里云OSS服务的存储桶名称
        String bucketName = aliyunOSSConfig.getBucketName();
        // 获取阿里云OSS服务的访问密钥ID
        String accessKeyId = aliyunOSSConfig.getAccessKeyId();
        // 获取阿里云OSS服务的访问密钥密钥
        String accessKeySecret = aliyunOSSConfig.getAccessKeySecret();
        // 以天为单位的名称，作为文件夹名称
        String newFolderName = DateUtil.format(new Date(), "yyyy-MM-dd");
        //以时间戳作为文件的新名称
        String newFileName = DateUtil.format(new Date(), "HHmmssSSS");
        // 获取上传文件的原始名称
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        // 获取并保留文件的后缀名
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 组合新的文件路径和名称
        String objectName = newFolderName + "/" + newFileName + fileSuffix;

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        URL url = null;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
            // 执行上传
            ossClient.putObject(putObjectRequest);
            // 创建上传文件访问的URL地址，设置URL过期时间为10年后
            url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(), 365 * 10));
        } catch (Exception ce) {
            // 输出异常信息
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            // 关闭OSSClient以释放资源。
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        // 返回文件的访问URL地址
        assert url != null;
        return url.toString();
    }
}